<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-28
 * Time: 9:49:37
 * Info: 后台登录日志
 */

namespace app\common\model;

use libs\IpToAddress;

class LoginLog extends TimeInit
{

    public static function getLogList($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $page  = $params['page'] ?? 1;
        $key   = $params['key'] ?? '';
        $first = ($page - 1) * $limit;

        $where = function ($query) use ($key) {
            if (isset($key['status']) && $key['status'] != '') {
                $query->where('status', $key['status']);
            }
            if ( ! empty($key['user_name'])) {
                $query->where('user_name', $key['user_name']);
            }
        };
        $count = self::where($where)->count();
        $list  = self::where($where)->limit($first, $limit)->order("id desc")->select()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['address']    = $v['country'].' '.$v['area'].' '.$v['city'].' '.$v['isp'];
            $list[$k]['os_vv']      = $v['os'].' '.$v['os_ver'];
            $list[$k]['browser_vv'] = $v['browser'].' '.$v['browser_ver'];
        }

        $data['list']  = $list ?? [];
        $data['count'] = $count ?? [];

        return $data;
    }

    /**
     * 写入后台登录日志
     *
     * @param $param
     *
     * @return bool
     */
    public static function createLoginLog($param = [])
    {
        if (empty($param)) {
            return false;
        }
        //判断后台设置是否写入登录日志
        if (get_config('login_log_admin') != 1) {
            return false;
        }

        $ip_address = $param['ip_address'] ?: '';
        $country    = '';
        $area       = '';
        $city       = '';
        $isp        = '';

        $ipToAdd = new IpToAddress();
        if ( ! empty($ip_address)) {
            //获取地区名：ip地址转换为地区名
            $res     = $ipToAdd->ipToAddress($ip_address);
            $country = $res['country'] ?? "";
            $area    = $res['province'] ?? "";
            $city    = $res['city'] ?? "";
            $isp     = $res['isp'] ?? "";
        }

        $data                = [];
        $data['user_id']     = $param['user_id'] ?: 0;
        $data['user_name']   = $param['user_name'] ?: '';
        $data['browser']     = $param['browser'] ?: '';
        $data['browser_ver'] = $param['browser_ver'] ?: '';
        $data['os']          = $param['os'] ?: '';
        $data['os_ver']      = $param['os_ver'] ?: '';
        $data['ip_address']  = $ip_address;
        $data['country']     = $country;
        $data['area']        = $area;
        $data['city']        = $city;
        $data['isp']         = $isp;
        $data['desc']        = $param['desc'] ?: '';
        $data['status']      = $param['status'] ?: 0;

        self::create($data);

        return true;
    }
}
